package org.outlook.test.ui.effect;

import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class DropTargetHandler implements DropTargetListener {
	
	public static void main(String[] args) {
		final JFrame frame = new JFrame();
		final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		frame.setPreferredSize(new Dimension(500,400));
		frame.setLocation((int)(screenSize.getWidth()-500)/2, (int)(screenSize.getHeight()-400)/2);
		frame.setAlwaysOnTop(true);
		frame.setVisible(true);
		frame.pack();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		JPanel panel = new JPanel();
		panel.setPreferredSize(new Dimension(500,400));
//		panel.setBackground(Color.RED);
		DropTarget dt = new DropTarget(panel, new DropTargetHandler());
		frame.setDropTarget(dt);
		frame.add(panel);
		
	}

	@Override
	public void dragEnter(DropTargetDragEvent event) {
		System.out.println("enter");
	}

	@Override
	public void dragExit(DropTargetEvent dte) {
		System.out.println("exit");
	}

	@Override
	public void dragOver(DropTargetDragEvent dtde) {
		System.out.println("over");
	}

	@SuppressWarnings({ "unchecked", "deprecation" })
	@Override
	public void drop(DropTargetDropEvent dtde) {
		dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
		if ((dtde.getDropAction() & DnDConstants.ACTION_COPY_OR_MOVE)==0) {
			 dtde.rejectDrop();   
            return;   
        }

		 Transferable transferable = dtde.getTransferable();
		 DataFlavor[] dataFlavors = dtde.getCurrentDataFlavors();
		 if(dataFlavors!=null && dataFlavors.length>0) {
			 if(dataFlavors[0].equals(DataFlavor.imageFlavor)) {//TODO
			 } else if(dataFlavors[0].isFlavorJavaFileListType() && 
					 dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
				 dataFlavors = null;
				 try {
					 List<File> list = (List<File>)transferable.getTransferData(DataFlavor.javaFileListFlavor);
					 System.out.println("get "+list.size()+" Files:");
					 for(File file:list) {
						 System.out.println('\t'+file.getAbsolutePath());//TODO
					 }
				 } catch (UnsupportedFlavorException e) {//TODO
				 } catch (IOException e) {//TODO 
				 }
			 } else if(dataFlavors[0].equals(DataFlavor.stringFlavor)) {//TODO			 
			 } else if(dataFlavors[0].equals(DataFlavor.javaSerializedObjectMimeType)) {//TODO			 
			 }
		 }
	}

	@Override
	public void dropActionChanged(DropTargetDragEvent dtde) {		 
	}

}
